package com.nuanshui.heatedloan.fund.integration.pay.execute.sysexecute;

import cn.beecloud.BCCache;
import cn.beecloud.BeeCloud;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.PayType;
import com.nuanshui.heatedloan.fund.integration.form.PayForm;
import com.nuanshui.heatedloan.fund.integration.pay.annotation.PayHandlerComponent;
import com.nuanshui.heatedloan.fund.integration.pay.execute.PayConfirmHandler;
import com.nuanshui.heatedloan.fund.model.PayResult;
import com.nuanshui.heatedloan.fund.model.PayResult.PayResultStatusType;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;

import java.io.UnsupportedEncodingException;

/**
 * 三方支付校验
 * @param 
 * @author guohao
 * @date 2017年1月10日 上午11:32:33
 * @since $
 */
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@PayHandlerComponent(order=100,value="authThreePartyPayConfirmHandler",nonsupportPayTypes={PayType.YE})
public class AuthThreePartyPayConfirmHandler implements PayConfirmHandler {

	private Logger logger= LoggerFactory.getLogger("pay_confirm");
	
	private String appId = "347cb5d4-e7b5-4e45-bdfb-d09eac7e0956";
	private String appSecret = "fd7b663c-fa51-4b9c-92c1-94bb3952fdd8";
	private PayConfirmHandler payConfirmHandler;
	@Override
	public PayResult executePaymentConfirm(PayForm payForm) {	
		LogUtil.info(logger, "三方支付回调");
		LogUtil.info(logger, "appId "+appId);
		LogUtil.info(logger, "appSecret "+appSecret);
		LogUtil.info(logger, "sign "+payForm.getSign());
		LogUtil.info(logger, payForm.getTimestamp());
		LogUtil.info(logger, "确认支付参数  "+JSON.toJSONString(payForm));
		BeeCloud.registerApp(appId, appSecret);
		
		boolean status = verifySign(payForm.getSign(), payForm.getTimestamp());
		LogUtil.info(logger, "校验结果  "+status);
		if(!status) {
			PayResult payResult = new PayResult();
			payResult.setStatus(PayResultStatusType.AUTH_FAIL);
			return payResult;
		}
		return payConfirmHandler.executePaymentConfirm(payForm);
	}
	
	private boolean verify(String sign, String text, String key, String input_charset) {

		text = text + key;
		String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));

		long timeDifference = System.currentTimeMillis() - Long.valueOf(key);
		if (mysign.equals(sign) && timeDifference <= 300000) {
			return true;
		} else {
			return false;
		}
	}

	private  boolean verifySign(String sign, String timestamp) {
		LogUtil.info(logger, "注册的appId  "+BCCache.getAppID());
		LogUtil.info(logger, "注册的appSecret  "+BCCache.getAppSecret());
		
		return verify(sign, BCCache.getAppID() + BCCache.getAppSecret(), timestamp, "UTF-8");
	}

	private byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("MD5验证失败:" + charset);
		}
	}

	@Override
	public void setPayConfirmHandler(PayConfirmHandler payConfirmHandler) {

		this.payConfirmHandler = payConfirmHandler;
	}
	
	public static void main(String[] args) {
		BeeCloud.registerApp("347cb5d4-e7b5-4e45-bdfb-d09eac7e0956", "fd7b663c-fa51-4b9c-92c1-94bb3952fdd8");
		AuthThreePartyPayConfirmHandler confirmHandler = new AuthThreePartyPayConfirmHandler();
		System.out.println(confirmHandler.verifySign("5182a6237510a282013db82b425e0373", "1484795160000"));
	}

}
